import router from './router'
import store from './store'
import { loginAndBack } from './utils/aaa'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { constantRoutes } from '@/router'


NProgress.configure({ showSpinner: false })

// const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  if (needAuthResult()) {
    await authResult(next)
    return
  }

  if (needLogin()) { // determine whether the user has logged in
    await store.dispatch('user/Logout')
    loginAndBack()
    return
  }
  checkPermission(to, from, next).then(() => {})

  //next()
})

router.afterEach(() => {
  NProgress.done()
})

function needLogin() {
  return !store.getters.name
}

function needAuthResult() {
  const url = top.location.href
  return url.indexOf('?auth_code=') > 0 || url.indexOf('&auth_code=') > 0
}

async function authResult(next) {
  const url = top.location.href
  console.log(url)
  const authCode = url.substring(url.indexOf('auth_code=') + 10)

  next(false) // 重要，不加会不刷新页面

  try {
    await store.dispatch('user/getAuthResult', authCode)
    await store.dispatch('user/GetInfo')
    const cleanUrl = url.substring(0, url.indexOf('auth_code=') - 1)
    console.log('-- cleanUrl --- ' + cleanUrl)
    // eslint-disable-next-line require-atomic-updates
    top.location.href = cleanUrl
  } catch (error) {
    console.log(error)
    alert(error)
  }
}

const checkPermission = async (to, from, next) => {
  const routes = store.getters.routes
  if (routes && routes.length) {
    if (to.matched.length) {
      next()
    } else {
      next('/404')
    }
  } else {
    //const permissionRoutes = await store.dispatch('user/getUserInfoByMock')
    const accessRoutes = await store.dispatch('permission/generateRoutes')
    router.addRoutes(accessRoutes)
    next({ ...to, replace: true })
  }
}
